<?php
namespace app\common\service\WebSocket\SocketService; 

use app\Normal;
use app\BaseService;
use app\common\service\SystemConfigService\Channel\ChannelConfigService;
use think\Container;
use app\model\BbcModel\Goods;
use app\model\BbcModel\GoodsBrand;
use app\model\BbcModel\GoodsClass;

class ActivitySocketService extends BaseService
{
    public $socket_connector;
    public $fd;
    public $host;
    public $pageLimit = 50;
    public $percent_status = [
        '1' => '写入中',
        '2' => '完成',
        '3' => '异常错误',
    ];
    
    public function goodsActivityImport($parameters) {
        $this->socket_connector = $parameters['socket'];
        $this->fd = $parameters['fd'];
        $this->host = $parameters['host'];
        ini_set('memory_limit', '3096M');
        //判断是否第一步
        $data = $parameters['requestData'];
        $data['cid']            = $parameters['_master_user']['cid'];
        //这里去获oss配置
        $oss = (new ChannelConfigService())->getConfigByCode(['cid'=>$data['cid'],'code'=>'ali_oss']);
        if($oss['code']!=200){
            $send = Normal::returnWsStatus(Normal::WS_ERROR, "oss未配置");
            $send = json_encode($send, JSON_UNESCAPED_UNICODE);            
            $this->socket_connector->push($this->fd, $send);
            return $send;
        }
        $xlsx = $oss['data']['url'] . '/' . $data['fileName'];
        //$xlsx = 'http://www.practice.com' . '/' . $data['fileName'];
        $string = explode('.', $data['fileName']);
        $ext = end($string);
        $content = file_get_contents($xlsx);//文件保存到本地
        $path = app()->getRootPath() . '/public/websocketservice/';
        $fileName = $path . date("YmdHis") . "." . $ext;
        file_put_contents($fileName, $content);
        //获取商品数据
        $XlsxData = ExcelImport($fileName, $ext,1);        
        $headerdata=$XlsxData[1];
        unset($XlsxData[1]);
        $chunk_data = array_chunk($XlsxData, $this->pageLimit);
        $total_page = count($chunk_data);
        $error_data = [];
        $goodsdata  = [];
        for ($page = 0; $page < $total_page; $page++) {
            
            foreach ($chunk_data[$page] as $i) {
                $goods= Goods::instance()->info(['skucode'=>$i[0],'cid'=>$data['cid']]);
                if($goods){
                    $goodsbrand= GoodsBrand::instance()->info(['id'=>$goods['brand_id']]);
                    $goodsclass= GoodsClass::instance()->info(['id'=>$goods['class_id']]);
                    $goodsinfo=$goods;
                    $goodsinfo['price_store']=$goods['price'];
                    $goodsinfo['goods_class_name']=$goodsclass['name']??'';
                    $goodsinfo['goods_brand_name']=$goodsbrand['name']??'';
                    $goodsinfo['is_bonded_name']=Goods::instance()->is_bonded[$goods['is_bonded']];
                    if($goods['num_storage']>0){
                        $goodsinfo['has_storage']='是';
                    }else{
                        $goodsinfo['has_storage']='否';
                    }
                    $goodsinfo['status_name']=$goods['status']==0?'下架':'上架';
                    $goodsdata[]=$goodsinfo;
                }else{
                    $error=$i;
                    $error[]='商品未找到';
                    $error_data[]=$error;
                }
            }
            if ($page == $total_page - 1) {
                $percent = 98.00;//预留给写文件使用
            } else {
                $percent = bcdiv($page, $total_page - 1, 4);
                $percent = bcmul($percent, 100, 2);
            }
            $send = Normal::returnWsStatus(Normal::WS_START, "进行中", ['download_url' => '',
                'msg' => '进行中',
                'percent' => $percent,
                'goodsdata'=>[]
            ]);
            $send = json_encode($send, JSON_UNESCAPED_UNICODE);
            $this->socket_connector->push($this->fd, $send);
        }
        
        //最后需要判断是否有错误数据
        if (!empty($error_data)) {
            //返回错误的表格
            $headArr = $headerdata;
            $headArr[] = '错误信息';
            $importFileName = "错误列表导出明细";
            $download_url = xlsxFileLocalStorage($headArr, $error_data, $importFileName, $this->host);
            return Normal::returnWsStatus(Normal::WS_END, "有错误数据", ['download_url' => $download_url,
                'msg' => "有错误数据",'name'=>'活动商品导入',
                'percent' => 100,'goodsdata'=>$goodsdata]);
        }

        return Normal::returnWsStatus(Normal::WS_END, "保存成功", [
            'download_url' => '',
            'msg' => "保存成功",
            'name'=>'活动商品导入',
            'percent' => 100,
            'goodsdata'=>$goodsdata
        ]);
    }
    
    public function seckillActivityImport($parameters) {
        $this->socket_connector = $parameters['socket'];
        $this->fd = $parameters['fd'];
        $this->host = $parameters['host'];
        ini_set('memory_limit', '3096M');
        //判断是否第一步
        $data = $parameters['requestData'];
        $data['cid']            = $parameters['_master_user']['cid'];
        //这里去获oss配置
        $oss = (new ChannelConfigService())->getConfigByCode(['cid'=>$data['cid'],'code'=>'ali_oss']);
        if($oss['code']!=200){
            $send = Normal::returnWsStatus(Normal::WS_ERROR, "oss未配置");
            $send = json_encode($send, JSON_UNESCAPED_UNICODE);            
            $this->socket_connector->push($this->fd, $send);
            return $send;
        }
        $xlsx = $oss['data']['url'] . '/' . $data['fileName'];
        //$xlsx = 'http://www.practice.com' . '/' . $data['fileName'];
        $string = explode('.', $data['fileName']);
        $ext = end($string);
        $content = file_get_contents($xlsx);//文件保存到本地
        $path = app()->getRootPath() . '/public/websocketservice/';
        $fileName = $path . date("YmdHis") . "." . $ext;
        file_put_contents($fileName, $content);
        //获取商品数据
        $XlsxData = ExcelImport($fileName, $ext,1);
        $headerdata=$XlsxData[1];
        unset($XlsxData[1]);
        $chunk_data = array_chunk($XlsxData, $this->pageLimit);
        $total_page = count($chunk_data);
        $error_data = [];
        $goodsdata  = [];
        for ($page = 0; $page < $total_page; $page++) {
            
            foreach ($chunk_data[$page] as $i) {
                $goods= Goods::instance()->info(['skucode'=>$i[0],'cid'=>$data['cid']]);
                if($goods){
                    $goodsbrand= GoodsBrand::instance()->info(['id'=>$goods['brand_id']]);
                    $goodsclass= GoodsClass::instance()->info(['id'=>$goods['class_id']]);
                    $goodsinfo=$goods;
                    $goodsinfo['price_store']=$goods['price'];
                    $goodsinfo['price']=$i[3];
                    $goodsinfo['goodsclassname']=$goodsclass['name']??'';
                    $goodsinfo['goodsbrandname']=$goodsbrand['name']??'';
                    $goodsinfo['is_bonded_name']=Goods::instance()->is_bonded[$goods['is_bonded']];
                    $goodsdata[]=$goodsinfo;
                }else{
                    $error=$i;
                    $error[]='商品未找到';
                    $error_data[]=$error;
                }
            }
            if ($page == $total_page - 1) {
                $percent = 98.00;//预留给写文件使用
            } else {
                $percent = bcdiv($page, $total_page - 1, 4);
                $percent = bcmul($percent, 100, 2);
            }
            $send = Normal::returnWsStatus(Normal::WS_START, "进行中", ['download_url' => '',
                'msg' => '进行中',
                'percent' => $percent,
                'goodsdata'=>[]
            ]);
            $send = json_encode($send, JSON_UNESCAPED_UNICODE);
            $this->socket_connector->push($this->fd, $send);
        }
        
        //最后需要判断是否有错误数据
        if (!empty($error_data)) {
            //返回错误的表格
            $headArr = $headerdata;
            $headArr[] = '错误信息';
            $importFileName = "错误列表导出明细";
            $download_url = xlsxFileLocalStorage($headArr, $error_data, $importFileName, $this->host);
            return Normal::returnWsStatus(Normal::WS_END, "有错误数据", ['download_url' => $download_url,
                'msg' => "有错误数据",'name'=>'秒杀商品导入',
                'percent' => 100,'goodsdata'=>$goodsdata]);
        }

        return Normal::returnWsStatus(Normal::WS_END, "保存成功", [
            'download_url' => '',
            'msg' => "保存成功",
            'name'=>'秒杀商品导入',
            'percent' => 100,
            'goodsdata'=>$goodsdata
        ]);
    }
    
    public function bookActivityImport($parameters) {
        $this->socket_connector = $parameters['socket'];
        $this->fd = $parameters['fd'];
        $this->host = $parameters['host'];
        ini_set('memory_limit', '3096M');
        //判断是否第一步
        $data = $parameters['requestData'];
        $data['cid']            = $parameters['_master_user']['cid'];
        //这里去获oss配置
        $oss = (new ChannelConfigService())->getConfigByCode(['cid'=>$data['cid'],'code'=>'ali_oss']);
        if($oss['code']!=200){
            $send = Normal::returnWsStatus(Normal::WS_ERROR, "oss未配置");
            $send = json_encode($send, JSON_UNESCAPED_UNICODE);            
            $this->socket_connector->push($this->fd, $send);
            return $send;
        }
        $xlsx = $oss['data']['url'] . '/' . $data['fileName'];
        //$xlsx = 'http://www.practice.com' . '/' . $data['fileName'];
        $string = explode('.', $data['fileName']);
        $ext = end($string);
        $content = file_get_contents($xlsx);//文件保存到本地
        $path = app()->getRootPath() . '/public/websocketservice/';
        $fileName = $path . date("YmdHis") . "." . $ext;
        file_put_contents($fileName, $content);
        //获取商品数据
        $XlsxData = ExcelImport($fileName, $ext,1);
        $headerdata=$XlsxData[1];
        unset($XlsxData[1]);
        $chunk_data = array_chunk($XlsxData, $this->pageLimit);
        $total_page = count($chunk_data);
        $error_data = [];
        $goodsdata  = [];
        for ($page = 0; $page < $total_page; $page++) {
            
            foreach ($chunk_data[$page] as $i) {
                $goods= Goods::instance()->info(['skucode'=>$i[0],'cid'=>$data['cid']]);
                if($goods){
                    $goodsbrand= GoodsBrand::instance()->info(['id'=>$goods['brand_id']]);
                    $goodsclass= GoodsClass::instance()->info(['id'=>$goods['class_id']]);
                    $goodsinfo=$goods;
                    $goodsinfo['price_store']=$goods['price'];
                    $goodsinfo['price']=$i[3]??0;
                    $goodsinfo['price_second']=$i[4]??0;
                    $goodsinfo['price_third']=$i[5]??0;
                    $goodsinfo['price_forth']=$i[6]??0;
                    $goodsinfo['goodsclassname']=$goodsclass['name']??'';
                    $goodsinfo['goodsbrandname']=$goodsbrand['name']??'';
                    $goodsinfo['is_bonded_name']=Goods::instance()->is_bonded[$goods['is_bonded']];
                    $goodsdata[]=$goodsinfo;
                }else{
                    $error=$i;
                    $error[]='商品未找到';
                    $error_data[]=$error;
                }
            }
            if ($page == $total_page - 1) {
                $percent = 98.00;//预留给写文件使用
            } else {
                $percent = bcdiv($page, $total_page - 1, 4);
                $percent = bcmul($percent, 100, 2);
            }
            $send = Normal::returnWsStatus(Normal::WS_START, "进行中", ['download_url' => '',
                'msg' => '进行中',
                'percent' => $percent,
                'goodsdata'=>[]
            ]);
            $send = json_encode($send, JSON_UNESCAPED_UNICODE);
            $this->socket_connector->push($this->fd, $send);
        }
        
        //最后需要判断是否有错误数据
        if (!empty($error_data)) {
            //返回错误的表格
            $headArr = $headerdata;
            $headArr[] = '错误信息';
            $importFileName = "错误列表导出明细";
            $download_url = xlsxFileLocalStorage($headArr, $error_data, $importFileName, $this->host);
            return Normal::returnWsStatus(Normal::WS_END, "有错误数据", ['download_url' => $download_url,
                'msg' => "有错误数据",'name'=>'拼团商品导入',
                'percent' => 100,'goodsdata'=>$goodsdata]);
        }

        return Normal::returnWsStatus(Normal::WS_END, "保存成功", [
            'download_url' => '',
            'msg' => "保存成功",
            'name'=>'拼团商品导入',
            'percent' => 100,
            'goodsdata'=>$goodsdata
        ]);
    }
}
